package com.wquick.base.utils

import android.app.Activity
import android.content.pm.ActivityInfo
import android.content.res.Resources
import android.os.Build
import android.view.Display


object DisUtility {

    //<editor-fold desc="禁用 7.0（23）以上字体大小和显示大小随系统变化">

    /**
     * 禁用7.0（23）以上显示大小改变和文字大小
     */
    fun disabledDisplayDpiChange(res: Resources): Resources {
        val newConfig = res.configuration
        val currentFontScale = res.configuration.fontScale
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //字体非默认值
            if (currentFontScale != 1f) {
//                newConfig.fontScale = fontScale(currentFontScale)
                newConfig.fontScale = fontScale(1f)
            }
            newConfig.densityDpi = defaultDisplayDensity
            res.updateConfiguration(newConfig, res.displayMetrics)
        } else {
            //字体非默认值
            if (currentFontScale != 1f) {
//                newConfig.fontScale = fontScale(currentFontScale) //设置默认
                newConfig.fontScale = fontScale(1f)
                res.updateConfiguration(newConfig, res.displayMetrics)
            }

        }
        return res
    }

    private fun fontScale(cur: Float): Float {
        var temp = 1f
        if (cur > 1) {
            temp = 1 + 1 * 0.15f
        }
        if (cur < 1) {
            temp = 1 - 1 * 0.15f
        }
        return temp
    }

    /**
     * 获取手机出厂时默认的densityDpi
     */
    private val defaultDisplayDensity: Int
        get() = try {
            val aClass = Class.forName("android.view.WindowManagerGlobal")
            val method = aClass.getMethod("getWindowManagerService")
            method.isAccessible = true
            val iwm = method.invoke(aClass)
            val getInitialDisplayDensity =
                iwm.javaClass.getMethod("getInitialDisplayDensity", Int::class.javaPrimitiveType)
            getInitialDisplayDensity.isAccessible = true
            val densityDpi = getInitialDisplayDensity.invoke(iwm, Display.DEFAULT_DISPLAY)
            densityDpi as Int
        } catch (e: Exception) {
            e.printStackTrace()
            -1
        }

    //</editor-fold>


    /**
     * 设置当前屏幕方向为横屏
     */
    fun setHorizontalScreen(activity: Activity) {
        if (activity.requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        }
    }

    /**
     * 设置当前屏幕方向为竖屏
     */
    fun setVerticalScreen(activity: Activity) {
        if (activity.requestedOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
        }
    }

}